<template>
	<view style="height: 100vh;">
		<view v-if="list.length>0">
			<u-tabs-swiper ref="uTabs" :bold="false" :list="list" :current="current" @change="tabsChange"
				:is-scroll="false" swiperWidth="750" active-color="#03C75A" inactive-color="#555555" height="88"
				font-size="32"></u-tabs-swiper>
		</view>
		<swiper :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
			<swiper-item class="swiper-item" :key="index" v-for="(x,index) in list">
				<Week v-if="current==index && x.type=='week'" />
				<Month v-if="current==index && x.type=='month'" />
				<Recommend v-if="current==index && x.type=='recommend'" />
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import Week from './category/week.vue'
	import Month from './category/month.vue'
	import Recommend from './category/recommend.vue'
	import * as Api from '@/api/assets/income/index.js'
	export default {
		components: {
			Week,
			Month,
			Recommend
		},
		data() {
			return {
				list: [],
				current: 0, // tabs组件的current值，表示当前活动的tab选项
				swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
				type: 'week',
			};
		},
		// watch: {
		// 	swiperCurrent(index) {
		// 		const type = this.list[index].type;
		// 	}
		// },
		onLoad(query) {
			const app = this;
			app.type = query.type || 'week';

			setTimeout(() => {
				if (app.list.length == 0) {
					console.log(1, app.type);
					app.getTabs();
				}
			}, 500);

			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('tabs', function(res) {
				console.log(2, app.type);
				app.getTabs(res);
			})
		},
		methods: {
			//没接收到tabs的时候，自动查询一下
			async getTabs(res) {
				const app = this;
				res = res || await Api.index();
				if (res.data) {
					app.list = res.data.list.map(item => ({
						name: item.title,
						type: item.type
					}))
					app.current = app.list.findIndex(item => item.type == app.type);
					app.tabsChange(app.current);
				}
			},
			// tabs通知swiper切换
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.uTabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
			},
		}
	}
</script>

<style lang="scss">
	swiper,
	uni-swiper,
	.swiper-item {
		min-height: calc(100vh - 88rpx)
	}
</style>